﻿using CCWin.SkinControl;
using ICSharpCode.SharpZipLib.Zip;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;
using System.Management;
using Tesseract;
using Newtonsoft.Json;

namespace CTOOLS
{
    public class PubFunClass
    {
        [DllImport("tesseract.dll")]
        unsafe public static extern int OCRDiscern(String image, String outputbase, String datapath, String lang, String sncode);
        //textBox1.Text=DateTime.Now.ToString("d");     //2009-09-06 
        //textBox2.Text=DateTime.Now.ToString("D");     //2009年09月06号
        //textBox3.Text=DateTime.Now.ToString("G");     //2009-09-06 10:56:13
        //textBox6.Text=DateTime.Now.ToString("g");     //2009-09-06 10:56
        //textBox5.Text=DateTime.Now.ToString("T");     //10:56:13
        //textBox4.Text=DateTime.Now.ToString("t");      //10:56

        //textBox12.Text=DateTime.Now.ToString("F");   //2009年09月06日 10:56:13
        //textBox11.Text=DateTime.Now.ToString("f");    //2009年09月06日 10:56
        //textBox10.Text=DateTime.Now.ToString("M");   //09月06日
        //textBox9.Text=DateTime.Now.ToString("R");     //Sun, 06 Sep 2009 10:56
        //textBox8.Text=DateTime.Now.ToString("s");     //2009-09-06T10:56:13
        //textBox7.Text=DateTime.Now.ToString("u");     //2009-09-06 10:56:13Z

        //textBox13.Text=DateTime.Now.ToString("Y");   //2009年09月
        //textBox14.Text=DateTime.Now.ToString("y");   //2009年09月
        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private static string ocrdataPath = @"C:\service\SrxWcfService\bin\tessdata";
        private static string EDKey = "ivHwE@20";
        #region 文件操作
        /// <summary>
        /// 选择目录
        /// </summary>
        /// <returns></returns>
        public static string GetSelectPath()
        {
            string sReturn = "";
            FolderBrowserDialog path = new FolderBrowserDialog();
            if( path.ShowDialog()== DialogResult.OK)
            {
                sReturn = path.SelectedPath;
            }
            return sReturn;
        }


        /// <summary>
        /// 获取目录下制定类型的所有文件
        /// </summary>
        /// <returns></returns>
        public static bool GetPathAllTypeFiles(ref FileInfo[] Afiles, string sPath,string sType)
        {
            bool bReturn = false;
            Afiles = null;
            try
            {
                DirectoryInfo Dir = new DirectoryInfo(sPath);
                if (Dir.Exists)
                {
                    Afiles = Dir.GetFiles(sType);
                    bReturn = true;
                }
                
            }
            catch (Exception ex)
            {
                log.Error("获取文件夹下文件失败!", ex);
            }
            return bReturn;
        }
        public static bool GetFileDirectory(string sFIle,ref string sDir)
        {
            sDir = "";
            bool bReturn = false;
            try
            {
                sDir = System.IO.Path.GetDirectoryName(sFIle);
                if(sDir.Substring(sDir.Length - 1, 1) !="\\")
                {
                    sDir = sDir + "\\";
                }
                bReturn = true;
            }
            catch (Exception ex)
            {
                log.Error("获取文件所在文件夹失败!", ex);
            }

            return bReturn;
        }

        /// <summary>
        /// 读取文件全部内容
        /// </summary>
        /// <param name="fPath"></param>
        /// <param name="splits"></param>
        /// <returns></returns>
        public static string GetFileReadAllLines(string fPath, string splits)
        {
            string sReturn = "";
            StreamReader sr = null;
            try
            {
                if (File.Exists(fPath))
                {
                    string allLines = "";
                    //读入文件
                    sr = new StreamReader(fPath, Encoding.Default);
                    while (!sr.EndOfStream)
                    {
                        string lines = sr.ReadLine();
                        if (lines.IsNullOrEmpty())
                        {
                            allLines = allLines + splits;
                        }
                        else
                        {
                            allLines = allLines + lines + splits;
                        }
                    }
                    //将datatable绑定到datagridview上显示结果
                    //skinDataGridViewTZS.DataSource = dt;
                    sReturn = allLines;
                }
            }
            catch (Exception ex)
            {
                log.Error("读取文件全部内容失败", ex);
            }
            finally
            {
                if (sr != null)
                {
                    sr.Close();
                }
            }
            return sReturn;
        }

        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="paths">起始路径</param>
        /// <param name="filters">文件类型</param>
        /// <param ref name="fileName">文件名称</param>
        /// <returns></returns>
        public static bool getFileDialog(string paths, string filters, ref string fileName, ref string fileFullName)
        {
            bool bReturn = false;
            fileFullName = "";
            fileName = "";
            try
            {
                OpenFileDialog fileDialog = new OpenFileDialog();
                fileDialog.InitialDirectory = paths;//"c://"
                fileDialog.Filter = filters;// "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                fileDialog.FilterIndex = 1;
                fileDialog.RestoreDirectory = true;
                if (fileDialog.ShowDialog() == DialogResult.OK)
                {
                    fileFullName = fileDialog.FileName;
                    fileName = fileDialog.SafeFileName;
                }
                bReturn = true;
            }
            catch (Exception ex)
            {
                log.Error("选择文件失败!", ex);
                //throw new Exception("出错!", ex);
            }
            return bReturn;
        }
        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="paths">起始路径</param>
        /// <param name="filters">文件类型</param>
        /// <param ref name="fileName">文件名称</param>
        /// <returns></returns>
        public static bool getFilesDialog(string paths, string filters, ref string[] fileName, ref string[] fileFullName)
        {
            bool bReturn = false;
            fileFullName = null;
            fileName = null;
            try
            {
                OpenFileDialog fileDialog = new OpenFileDialog();
                fileDialog.InitialDirectory = paths;//"c://"
                fileDialog.Filter = filters;// "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                fileDialog.FilterIndex = 1;
                fileDialog.RestoreDirectory = true;
                fileDialog.Multiselect = true;
                if (fileDialog.ShowDialog() == DialogResult.OK)
                {
                    fileFullName = fileDialog.FileNames;
                    fileName = fileDialog.SafeFileNames;
                }
                bReturn = true;
            }
            catch (Exception ex)
            {
                log.Error("选择文件失败!", ex);
                //throw new Exception("出错!", ex);
            }
            return bReturn;
        }

        public static bool getSaveFileDialog(string paths, string filters, ref string fileName)
        {
            bool bReturn = false;
            fileName = "";
            try
            {
                SaveFileDialog fileDialog = new SaveFileDialog();
                //fileDialog.InitialDirectory = paths;//"c://"
                //fileDialog.Filter = "Excel(97-2003)|*.xls|Excel(2007-2013)|*.xlsx";
                //fileDialog.Filter = filters;// "Excel|*.xls|Excel|*.xlsx";
                fileDialog.InitialDirectory = paths;//"c://"
                fileDialog.Filter = filters;// "txt files (*.txt)|*.txt|All files (*.*)|*.*";
                fileDialog.FilterIndex = 1;
                fileDialog.RestoreDirectory = true;
                if (fileDialog.ShowDialog() == DialogResult.OK)
                {
                    fileName = fileDialog.FileName;
                }
                bReturn = true;
            }
            catch (Exception ex)
            {
                log.Error("选择文件失败!", ex);
                //throw new Exception("出错!", ex);
            }
            return bReturn;
        }

        /// <summary>
        /// 判断文件是否被打开
        /// </summary>
        /// <param name="pathName"></param>
        /// <returns></returns>
        public static bool isFileLocked(string pathName)
        {
            try
            {
                if (!File.Exists(pathName))
                {
                    return false;
                }

                using (var fs = new FileStream(pathName, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    fs.Close();
                }
            }
            catch
            {
                return true;
            }
            return false;
        }

        /// <summary>   
        ///创建文件夹   
        /// 用法： CreateFolder(@"c:\\1");   
        /// </summary>   
        /// <param name="dir"></param>   
        public static bool CreateFolder(string dir)
        {
            bool bReturn = false;
            try
            {
                if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
                bReturn = true;
            }
            catch (Exception ex)
            {
                log.Error("拷贝文件夹失败!", ex);
                //throw new Exception("出错!", ex);
            }
            return bReturn;
        }

        /// <summary>   
        ///删除文件夹   
        /// 用法： DeleteFolder(@"c:\\1");   
        /// </summary>   
        /// <param name="dir"></param>   
        public static bool DeleteFolder(string dir)
        {
            bool bReturn = false;
            try
            {
                // 循环文件夹里面的内容   
                foreach (string f in Directory.GetFileSystemEntries(dir))
                {
                    // 如果是文件存在   
                    if (File.Exists(f))
                    {
                        FileInfo fi = new FileInfo(f);
                        if (fi.Attributes.ToString().IndexOf("Readonly") != 1)
                        {
                            fi.Attributes = FileAttributes.Normal;
                        }
                        //直接删除其中的文件   
                        File.Delete(f);
                    }
                    else
                    {
                        // 如果是文件夹存在   
                        // 递归删除子文件夹   
                        DeleteFolder(f);
                    }
                }
                // 删除已空文件夹   
                Directory.Delete(dir);
                bReturn = true;
            }
            catch (Exception ex)
            {
                log.Error("删除文件夹失败!", ex);
                //throw new Exception("出错!", ex);
            }
            return bReturn;
        }

        /// <summary>
        /// 拷贝文件夹
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        public static bool CopyFolder(string from, string to)
        {
            bool bReturn = false;
            try
            {
                if (!Directory.Exists(to)) Directory.CreateDirectory(to);
                // 子文件夹
                foreach (string sub in Directory.GetDirectories(from))
                    CopyFolder(sub + "\\", to + Path.GetFileName(sub) + "\\");
                // 文件
                foreach (string file in Directory.GetFiles(from))
                    File.Copy(file, to + Path.GetFileName(file), true);
                bReturn = true;
            }
            catch (Exception ex)
            {
                log.Error("拷贝文件夹失败!", ex);
                //throw new Exception("出错!", ex);
            }
            return bReturn;
        }

        /// <summary>
        /// 拷贝文件
        /// </summary>
        /// <param name="from"></param>
        /// <param name="to"></param>
        /// <returns></returns>
        public static bool CopyFile(string from, string to)
        {
            bool bReturn = false;
            try
            {
                if (File.Exists(from))
                {
                    File.Copy(from, to, true);
                    bReturn = true;
                }  
            }
            catch (Exception de)
            {
                log.Error("拷贝文件失败!", de);
            }
            return bReturn;
        }
        /// <summary>
        /// 文字写入文件https://www.cnblogs.com/stilldream/p/10044011.html
        /// </summary>
        /// <param name="fileC">文字内容</param>
        /// <param name="fileP">文件路径E:\123\456.txt</param>
        /// <returns></returns>
        public static bool SWriterFile(string fileC,string fileP)
        {
            bool bReturn = false;
            try
            {
                using (StreamWriter sw = new StreamWriter(fileP, false, Encoding.UTF8))
                {
                    //byte[] mybyte = Encoding.UTF8.GetBytes(fileC);
                    //text1.Text = Encoding.UTF8.GetString(mybyte);
                    sw.Write(fileC);
                    bReturn = true;
                }

            }
            catch (Exception de)
            {
                log.Error("写入文件失败!", de);
            }
            return bReturn;
        }
        public static bool ChangeFileName(string srcFileName, string destFileName)
        {
            bool bReturn = false;
            try
            {
                if (File.Exists(srcFileName))
                {
                    File.Move(srcFileName, destFileName);
                    bReturn = true;
                }
            }
            catch (Exception de)
            {
                log.Error("修改文件名称失败!", de);
            }
            return bReturn;
        }
        /// 打开任意文件
        /// </summary>
        /// <param name="OpenFile"></param>
        /// <returns></returns>
        public static bool OpenFile(string OpenFile)
        {
            bool bReturn = false;
            try
            {
                System.Diagnostics.Process.Start(OpenFile);
                bReturn = true;
            }
            catch (Exception ex)
            {
                log.Error("打开文件失败", ex);
            }
            return bReturn;
        }


        /// <summary>
        /// 判断字符串是否为数字
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        public static bool StrToNumeric(string number, ref int num)
        {
            try
            {
                num = int.Parse(number);
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 获取字符串中的数字
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetStrNum(string str)
        {
            try
            {
                //Regex.Replace(str, @"[^0-9]+", "");纯数字提取
                return Regex.Replace(str, @"[^\d.\d]", "");//带有小数点数字提取
            }
            catch
            {
                return str;
            }
        }
        #endregion


    }
}